//
//  SRHomewokRecordViewController.m
//  StoryShow
//
//  Created by CyonLeuMBP on 2017/9/11.
//  Copyright © 2017年 qudiandu.cn. All rights reserved.
//

#import "SRHomewokRecordViewController.h"
#import "FZIconImageView.h"
#import "SRSchoolClassServices.h"
#import "SRHomeworkAnswerModel.h"
#import "SRHomeworkDetailItemModel.h"

#import "SRSpeakingDatabaseManager.h"
#import "FZMCCacheManager.h"
#import "SRAudioPlayerManager.h"
#import "SRHomeworkPictureModel.h"
#import <FZIconImageView.h>

@interface SRHomewokRecordViewController ()

@property (weak, nonatomic) IBOutlet UIView *bottomContentView;

@property (weak, nonatomic) IBOutlet UIView *centerContentView;
@property (weak, nonatomic) IBOutlet FZIconImageView *iconImageView;
@property (weak, nonatomic) IBOutlet UIButton *playButton;


@property (weak, nonatomic) IBOutlet UILabel *startTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *endTimeLabel;
@property (weak, nonatomic) IBOutlet UISlider *playProgressSlider;
@property (weak, nonatomic) IBOutlet UIButton *bottomPlayButton;

@property (strong, nonatomic) SRHomeworkDetailItemModel *detialModel;
@property (strong, nonatomic) SRHomeworkPictureModel *currentItemModel;
@property (assign, nonatomic) BOOL isPlaying;
@property (assign, nonatomic) BOOL playButtonHidden;


@property (weak, nonatomic) IBOutlet UIView *topContentView;
@property (weak, nonatomic) IBOutlet UIView *topSeperatorView;

@property (weak, nonatomic) IBOutlet FZIconImageView *userIconImageView;
@property (weak, nonatomic) IBOutlet UILabel *nicknameLabel;
@property (weak, nonatomic) IBOutlet UILabel *gradeLabel;
@property (weak, nonatomic) IBOutlet UILabel *learnTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *prelearnTimeLabel;
@property (weak, nonatomic) IBOutlet UILabel *problemTitleLabel;

@property (assign, nonatomic) BOOL isFinished;
@property (assign, nonatomic) NSInteger currentPlayTime;


@property (strong, nonatomic) UIButton *nextButton;

@property (strong, nonatomic) UIView *bottomView;
@property (strong, nonatomic) UIButton *previousButton;
@property (assign, nonatomic) BOOL sliderIsChanging;

@property (strong, nonatomic) NSTimer *timer;


@end

@implementation SRHomewokRecordViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self setupView];
    [self setupBottomView];
    
    [self.userIconImageView fz_setAvatarImageWithUrlString:[SRLoginUser avatar]];
    self.userIconImageView.borderWidth = 0;
    
    self.nicknameLabel.text = [SRLoginUser nickname];
    
    NSMutableString *text = [[NSMutableString alloc] init];
    NSString *gradeString = [SRLoginUser schoolGrade];
    if (gradeString) {
        [text appendFormat:@"%@年级", gradeString];
    }
    
    NSInteger age = [SRLoginUser age];
    if (age > 0) {
        [text appendFormat:@"%d岁", age];
    }
    
    self.gradeLabel.text = text;
    self.learnTimeLabel.text = @"00:00:00";
    
    [self startProgressHUD];
    
    if (self.isFinishedDetail) {
        [self queryDataFinishDetail];
    } else {
        [self queryData];
        
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimerAction:) userInfo:nil repeats:YES];
        [self.timer setFireDate:[NSDate distantFuture]];
    }
    
    

}

- (void)dealloc {
    if (!self.isFinishedDetail && self.currentItemModel && self.currentPlayTime > 0) {
        NSString *problemID = [NSString stringWithFormat:@"%@", self.currentItemModel.problem_id];
        [SRSpeakingDatabaseManager updateAudioWithID:problemID learnTime:self.currentPlayTime];
    }
    
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
 
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [[SRAudioPlayerManager sharedInstance] stopPlayRecordAudio];
    if (self.timer) {
        [self.timer invalidate];
        self.timer = nil;
    }
    
}



- (void)setupView {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    self.view.backgroundColor = css.color_2;
    
    self.centerContentView.backgroundColor = [UIColor colorWithWhite:1 alpha:0.2];
    self.centerContentView.layer.cornerRadius = 275/2.0;
    
    self.iconImageView.iconStyle = FZIconImageViewStyleCircle;
    self.iconImageView.borderWidth = 0;
    
    [self.playProgressSlider setThumbImage:[UIImage imageNamed:@"progressBar"] forState:UIControlStateNormal];
    self.playProgressSlider.minimumTrackTintColor = css.color_7;
    self.playProgressSlider.maximumTrackTintColor = css.color_4;
    
    [self.playProgressSlider addTarget:self action:@selector(sliderTouchDown:) forControlEvents:UIControlEventTouchDown];
    [self.playProgressSlider addTarget:self action:@selector(sliderValueChangedEnd:) forControlEvents: UIControlEventTouchUpInside | UIControlEventTouchCancel];
    [self.playProgressSlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    
    self.startTimeLabel.textColor = css.color_7;
    
    WEAKSELF
    [self.view addTapGestureHandler:^(UITapGestureRecognizer *gestureRecognizer, UIView *view, CGPoint locationInView) {
        if (weakSelf.playButtonHidden) {
            weakSelf.playButtonHidden = NO;
        } else {
            weakSelf.playButtonHidden = YES;
        }
    }];
    
    self.playButtonHidden = NO;
    
    self.topContentView.backgroundColor = [UIColor clearColor];
    self.topSeperatorView.backgroundColor = css.color_9;
    self.iconImageView.iconStyle = FZIconImageViewStyleCircle;
    
    self.nicknameLabel.textColor = [UIColor whiteColor];
    self.prelearnTimeLabel.textColor = self.learnTimeLabel.textColor = self.gradeLabel.textColor = [UIColor colorWithHex:0xffffff withAlpha:0.7];
    
}


- (void)setupBottomView {
    
    FZStyleSheet *css = [FZStyleSheet currentStyleSheet];
    UIView *bottomView = [[UIView alloc] init];
    bottomView.backgroundColor = [UIColor colorWithHex:0x4e4033];
    self.bottomView = bottomView;
    [self.view addSubview:bottomView];
    
    UIButton *preButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [preButton setTitle:@"上一题" forState:UIControlStateNormal];
    preButton.titleLabel.font = css.fontOfH5;
    [preButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [preButton addTarget:self action:@selector(onPreButton:) forControlEvents:UIControlEventTouchUpInside];
    self.previousButton = preButton;
    [self.bottomView addSubview:preButton];
    
    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [nextButton setTitle:@"下一题" forState:UIControlStateNormal];
    nextButton.titleLabel.font = css.fontOfH5;
    [nextButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(onNextButton:) forControlEvents:UIControlEventTouchUpInside];
    self.nextButton = nextButton;
    [self.bottomView addSubview:nextButton];
    
    [self.previousButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.bottom.equalTo(self.bottomView);
        make.width.mas_equalTo(60);
    }];
    
    [self.nextButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.top.bottom.equalTo(self.bottomView);
        make.width.mas_equalTo(60);
    }];
    
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
}


- (void)setPlayButtonHidden:(BOOL)playButtonHidden {
    _playButtonHidden = playButtonHidden;
    
    self.playButton.hidden = playButtonHidden;
    
    if (!playButtonHidden) {
        [self performSelector:@selector(updatePlayHidden) withObject:nil afterDelay:3];
    }
}


- (void)updatePlayButtonStatus:(BOOL)isPlaying {
    if (isPlaying) {
        [self.playButton setImage:[UIImage imageNamed:@"icon-stop-big"] forState:UIControlStateNormal];
        [self.bottomPlayButton setImage:[UIImage imageNamed:@"icon-stop"] forState:UIControlStateNormal];
    } else {
        [self.playButton setImage:[UIImage imageNamed:@"icon-play-big"] forState:UIControlStateNormal];
        [self.bottomPlayButton setImage:[UIImage imageNamed:@"icon-play"] forState:UIControlStateNormal];
    }
}

#pragma mark - QueryData


- (void)queryData{
    WEAKSELF
    [SRSchoolClassServices queryProblemDetailWithTaskID:self.taskID SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
            //            [weakSelf.tableView.footer endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            weakSelf.detialModel = responseDataObject;
        
            [weakSelf updateInfo];
//            [weakSelf parseQuestionModel:weakSelf.detialModel];
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
            //            [weakSelf.tableView.footer endRefreshing];
        [weakSelf stopProgressHUD];
        
    }];
    
}


- (void)queryDataFinishDetail{
    WEAKSELF
    [SRSchoolClassServices queryProblemFinishDetailWithFinishID:self.taskID SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
        [weakSelf stopProgressHUD];
            //            [weakSelf.tableView.footer endRefreshing];
        
        if (statusCode == kFZRequestStatusCodeSuccess && responseDataObject) {
            weakSelf.detialModel = responseDataObject;
            
            [weakSelf updateInfo];
        } else {
            [weakSelf showHUDErrorMessage:message];
        }
        
    } failureBlock:^(id responseObject, NSError *error) {
            //            [weakSelf.tableView.footer endRefreshing];
        [weakSelf stopProgressHUD];
        
    }];
    
}

- (void)updateInfo {
    
    self.title = self.detialModel.title;
    
    for (int i = 0; i < [self.detialModel.problems count]; ++ i) {
        SRHomeworkPictureModel *item = self.detialModel.problems[i];
        item.index = i;
        item.task_id = self.taskID;
    }
    
    if (!self.isFinishedDetail) {
        [self updateAudioPlayProgressWithItems:self.detialModel.problems];
    }
    
    if ([self.detialModel.problems count] > 0) {
        SRHomeworkPictureModel *firstItem = [self.detialModel.problems firstObject];
        self.currentItemModel = firstItem;
        
        CABasicAnimation *animation;
        animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
        animation.fromValue = [NSNumber numberWithFloat:0.0];
        animation.toValue = [NSNumber numberWithFloat:2 * M_PI];
        animation.timingFunction = [CAMediaTimingFunction functionWithName: kCAMediaTimingFunctionLinear];
        animation.repeatCount = NSIntegerMax;
        animation.duration = 60;
        [self updateCurrentItemInfo:self.currentItemModel];
    }
}

- (void)updateAudioPlayProgressWithItems:(NSArray *)items {
    
    NSArray *dataArray = [SRSpeakingDatabaseManager searchAudioModelsWithTaskID:self.taskID];
    if (!dataArray || [dataArray count] == 0) {
        return;
    }
    
    for (SRHomeworkPictureModel *dbItem in dataArray) {
        
        for (SRHomeworkPictureModel *model in items) {
            if ([dbItem.problem_id longLongValue] == [model.problem_id longLongValue]) {
                model.playProgress = dbItem.playProgress;
                model.isPlayFinished = dbItem.isPlayFinished;
                model.learnTime = dbItem.learnTime;
                
                NSLog(@"******updateAudioPlayProgressWithItems:%@**%@**finish:%d", model.problem_id, model.title, model.isPlayFinished);
                
            }
        }
    }
}


- (void)updateCurrentItemInfo:(SRHomeworkPictureModel *)item {
    
    self.problemTitleLabel.text = item.title;
    [self updatenextButtonTitle];
    
    if (self.isFinishedDetail) {
        NSInteger learnTime = [self.currentItemModel.answerByUser longLongValue];
        self.learnTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", learnTime / 60, learnTime % 60];
    } else {
        NSInteger learnTime = self.currentItemModel.learnTime;
        self.learnTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", learnTime / 60, learnTime % 60];
    }
    
    if (!self.isFinishedDetail) {
        [SRSpeakingDatabaseManager saveAudioModel:item];
    }
    
    self.currentPlayTime = item.learnTime;
    [self.iconImageView fz_setImageWithDefaultPlaceholderWithURLString:self.currentItemModel.pic];
    
  
    self.startTimeLabel.text = @"00:00";
    NSInteger timeStamp = [self.currentItemModel.audio_timelen longLongValue];
    self.endTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", timeStamp / 60, timeStamp % 60];
    self.isPlaying = YES;
    [self updatePlayButtonStatus:YES];
    
    SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
    
    [audioPlayer setRecordAudioWithFileURL:self.currentItemModel.audio];
    [self.timer setFireDate:[NSDate date]];
//    [self.timer fire];
    
    WEAKSELF
    audioPlayer.audioPlayerProgressBlock = ^(CGFloat progress) {
        if (!weakSelf.sliderIsChanging) {
            [weakSelf.playProgressSlider setValue:progress];
        }
        weakSelf.currentItemModel.playProgress = progress;
        NSString *problemID = [NSString stringWithFormat:@"%@", weakSelf.currentItemModel.problem_id];
        
        [SRSpeakingDatabaseManager updateAudioWithID:problemID playProgress:progress];
    };
    
    audioPlayer.audioPlayerTimeBlock = ^(CGFloat time) {
        NSInteger timeStamp = time;
//        weakSelf.currentPlayTime = time;
        
        weakSelf.startTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", timeStamp / 60, timeStamp % 60];
//        if (!weakSelf.isFinishedDetail) {
//            weakSelf.learnTimeLabel.text = weakSelf.startTimeLabel.text;
//        }
        
    };
    
    audioPlayer.audioPlayerCompletedBlock = ^(BOOL finish) {
//        if (finish) {
            weakSelf.currentItemModel.isPlayFinished = finish;
//            weakSelf.currentPlayTime = [weakSelf.currentItemModel.audio_timelen floatValue];
        NSString *problemID = [NSString stringWithFormat:@"%@", weakSelf.currentItemModel.problem_id];

        if (!weakSelf.isFinishedDetail) {
            weakSelf.currentItemModel.answerByUser = [NSString stringWithFormat:@"%ld", (long)weakSelf.currentPlayTime];
            weakSelf.currentItemModel.learnTime = weakSelf.currentPlayTime;
            
            [SRSpeakingDatabaseManager updateAudioWithID:problemID learnTime:weakSelf.currentPlayTime];
          
            [weakSelf.timer setFireDate:[NSDate distantFuture]];
        }
        [SRSpeakingDatabaseManager updateAudioWithID:problemID playProgress:1];
        [SRSpeakingDatabaseManager updateAudioWithID:problemID playFinish:YES];
//        }
    };
    
    [self performSelector:@selector(updatePlayHidden) withObject:nil afterDelay:3];
}


#pragma mark - Event

- (void)onPreButton:(UIButton *)sender {
    if (self.currentItemModel.index > 0 && self.currentItemModel.index < [self.detialModel.problems count] ) {
        
        if (!self.isFinishedDetail) {
            self.currentItemModel.answerByUser = [NSString stringWithFormat:@"%ld", self.currentPlayTime];
            self.currentItemModel.learnTime = self.currentPlayTime;
            
            NSString *problemID = [NSString stringWithFormat:@"%@", self.currentItemModel.problem_id];
            [SRSpeakingDatabaseManager updateAudioWithID:problemID learnTime:self.currentPlayTime];
            
        }
        self.currentItemModel = self.detialModel.problems[self.currentItemModel.index - 1];
        [self updateCurrentItemInfo:self.currentItemModel];
    } else {
        [self showHUDHintWithText:@"已经是第一题"];
    }
}

- (void)onNextButton:(id)sender {
    
    if (self.currentItemModel.index == ([self.detialModel.problems count]-1) ) {
        
        if (self.isFinishedDetail) {
                //完成返回；
            UIViewController *destVC = nil;
            for (UIViewController *vc in self.navigationController.viewControllers) {
                if ([vc isKindOfClass:NSClassFromString(@"SRClassHomeWorkDetailViewController")]) {
                    destVC = vc;
                    break;
                }
            }
            
            if (destVC) {
                [self.navigationController popToViewController:destVC animated:YES];
            } else {
                [self.navigationController popToRootViewControllerAnimated:YES];
            }
            
            return;
        }
            //若当前是最后一题，则提交
        if (self.currentPlayTime > 0 && !self.isFinishedDetail) {
            self.currentItemModel.answerByUser = [NSString stringWithFormat:@"%ld", self.currentPlayTime];
            self.currentItemModel.learnTime = self.currentPlayTime;
            NSString *problemID = [NSString stringWithFormat:@"%@", self.currentItemModel.problem_id];
            [SRSpeakingDatabaseManager updateAudioWithID:problemID learnTime:self.currentPlayTime];
        }
        
        NSMutableDictionary *answerDict = [NSMutableDictionary dictionaryWithCapacity:4];
        for (SRHomeworkPictureModel *item in self.detialModel.problems) {
            [answerDict setValue:item.answerByUser forKey:item.problem_id];
        }
        
        if ([[answerDict allKeys] count] <= 0) {
            [self showHUDHintWithText:@"你还没有选择答案，请选择后再提交。"];
            return;
        }
        
        [self startProgressHUDWithText:@"提交中..."];
        
        self.isFinished = YES;
        
        NSError *error;
        NSString *answer = nil;
        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:answerDict options:NSJSONWritingPrettyPrinted error:&error];
        if (! jsonData) {
                //转化失败
        } else {
            answer = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        }
        
        WEAKSELF
        [SRSchoolClassServices submitProblemAnswerWithTaskID:self.taskID groupID:self.detialModel.group_id answer:answer SuccessBlock:^(NSInteger statusCode, NSString *message, id responseDataObject) {
            [weakSelf stopProgressHUD];
            if (statusCode == kFZRequestStatusCodeSuccess) {
                [weakSelf showHUDHintWithText:@"提交成功"];
                [weakSelf performSelector:@selector(doBack) withObject:nil afterDelay:1];
                
            } else {
                [weakSelf showHUDHintWithText:message];
            }
        } failureBlock:^(id responseObject, NSError *error) {
            [weakSelf stopProgressHUD];
            [weakSelf showHUDError];
        }];
        
        
    } else{
            //下一题
        if (self.currentItemModel.index < [self.detialModel.problems count]) {
            if (!self.isFinishedDetail) {
                self.currentItemModel.answerByUser = [NSString stringWithFormat:@"%ld", self.currentPlayTime];
                
                self.currentItemModel.learnTime = self.currentPlayTime;
                
                NSString *problemID = [NSString stringWithFormat:@"%@", self.currentItemModel.problem_id];
                [SRSpeakingDatabaseManager updateAudioWithID:problemID learnTime:self.currentPlayTime];
                
            }

            
            self.currentItemModel = self.detialModel.problems[self.currentItemModel.index + 1];
            
            [self updateCurrentItemInfo:self.currentItemModel];
        }
    }
}


- (void)updatePlayHidden {
    self.playButtonHidden = YES;
}

    //暂停动画
- (void)pauseAnimation {
    
        //（0-5）
        //开始时间：0
        //    myView.layer.beginTime
        //1.取出当前时间，转成动画暂停的时间
    CFTimeInterval pauseTime = [self.iconImageView.layer convertTime:CACurrentMediaTime() fromLayer:nil];
    
        //2.设置动画的时间偏移量，指定时间偏移量的目的是让动画定格在该时间点的位置
    self.iconImageView.layer.timeOffset = pauseTime;
    
        //3.将动画的运行速度设置为0， 默认的运行速度是1.0
    self.iconImageView.layer.speed = 0;
    
}

    //恢复动画
- (void)resumeAnimation {
    
        //1.将动画的时间偏移量作为暂停的时间点
    CFTimeInterval pauseTime = self.iconImageView.layer.timeOffset;
    
        //2.计算出开始时间
    CFTimeInterval begin = CACurrentMediaTime() - pauseTime;
    
    [self.iconImageView.layer setTimeOffset:0];
    [self.iconImageView.layer setBeginTime:begin];
    
    self.iconImageView.layer.speed = 1;
}


- (IBAction)onTouchAudioPlayButton:(id)sender {
    SRAudioPlayerManager *audioPlayer = [SRAudioPlayerManager sharedInstance];
    
    if (audioPlayer.isPlaying) {
        self.isPlaying = NO;
        [audioPlayer pauseRecordAudio];
        [self pauseAnimation];
        
        if (!self.isFinishedDetail) {
            [self.timer setFireDate:[NSDate distantFuture]];
        }
        
    } else {
        self.isPlaying = YES;
        [self resumeAnimation];
        if (!self.isFinishedDetail) {
            [self.timer setFireDate:[NSDate date]];
        }
        NSString *url = self.currentItemModel.audio;
        if ([audioPlayer playingFileName] && [[audioPlayer playingFileName] isEqualToString:[url lastPathComponent]]) {
            [audioPlayer startPlayRecordAudio];
        } else {
            
            [[SRAudioPlayerManager sharedInstance] setRecordAudioWithFileURL:url];
        }
    }
    
    [self updatePlayButtonStatus:self.isPlaying];
}

- (void)updatenextButtonTitle {
    if (self.currentItemModel.index == ([self.detialModel.problems count]-1) ) {
            //最后一个问题，
        if (self.isFinishedDetail) {
            [self.nextButton setTitle:@"完成" forState:UIControlStateNormal];
        } else {
            [self.nextButton setTitle:@"提交" forState:UIControlStateNormal];
        }
    } else {
        [self.nextButton setTitle:@"下一题" forState:UIControlStateNormal];
    }
}

- (void)sliderTouchDown:(UISlider *)slider {
    self.sliderIsChanging = YES;
   
}

- (void)sliderValueChangedEnd:(UISlider *)slider {
    
    [[SRAudioPlayerManager sharedInstance] setRecordAudioProgress:slider.value autoPlay:YES];
    
    self.sliderIsChanging = NO;
}

- (void)sliderValueChanged:(UISlider *)slider {
   
}

- (void)onTimerAction:(id)sender {
    self.currentPlayTime += 1;
//    NSLog(@"******onTimerAction:%ld", self.currentPlayTime);
    if (!self.isFinishedDetail) {
        NSInteger learnTime = self.currentPlayTime;
        self.learnTimeLabel.text = [NSString stringWithFormat:@"%02lld:%02lld", learnTime / 60, learnTime % 60];
    }
   
}

@end
